<template>
  <div ref="blogOverviewRef" class="blog-content-list blog-section common-mobile-view">
    <div v-if="blogStore.blogList.length === 0"
         class="blog-content blog-content-empty" >
    </div>

    <div class="blog-content blog-content-summary card-item"
         v-for="(item, index) in blogStore.blogList" :key="index">
      <span class="title">{{ item.title }}</span>

      <blog-label :basic-blog="getBasicBlog(item)"/>

      <p class="content">
        {{ item.summary }}
      </p>

      <el-button type="primary" @click="readBlogClick(index)">阅读全文 »</el-button>
      <hr/>
    </div>

    <arrive-bottom v-if="blogStore.isScrollEnd"/>
  </div>
</template>

<script setup lang="ts">
import BlogLabel from '@/components/Blog/Content/BlogLabel.vue'
import ArriveBottom from '@/components/Common/ArriveButton.vue'
import { useRouter } from 'vue-router'
import { onBeforeUnmount, onMounted, ref } from 'vue'
import { useBlogStore } from '@/store/blog.ts'
import { getBasicBlog } from '@/utils/blog/blogUtil.ts'

const blogOverviewRef = ref()
const router = useRouter()
const blogStore = useBlogStore()

onMounted(async () => {
  blogStore.pageInfo = {
    currentPage: 1,
    pageSize: 3,
    totalSize: 1
  }
  blogStore.blogList = []
  await blogStore.queryMobileBlog()
  blogOverviewRef.value.addEventListener('scroll', handleScroll)
})

onBeforeUnmount(() => {
  blogOverviewRef.value.removeEventListener('scroll', handleScroll)
})

/**
 * 点击阅读博客按钮
 * @param index 索引
 */
const readBlogClick = async (index: number) => {
  const blogId = blogStore.blogList[index].id
  await router.push({ name: 'BlogDetailId', params: { id: blogId } })
}

const handleScroll = () => {
  const el = blogOverviewRef.value
  if (el.scrollTop + el.clientHeight >= el.scrollHeight - 10) {
    const { currentPage, pageSize, totalSize } = blogStore.pageInfo
    blogStore.isScrollEnd = pageSize * currentPage > totalSize
    if (!blogStore.isScrollEnd) {
      blogStore.pageInfo.currentPage++
      blogStore.queryMobileBlog()
    }
  }
}
</script>

<style lang="scss">
@use "@/styles/blog/blog.overview.module";
</style>
